<template>
  <view class="revenue-page">
    <!-- 导航栏 - 使用定义的渐变背景 -->
    <s-nav-bar title="营业额明细分析" :background="'var(--v-linear)'"
      :titleStyle="{ color: 'var(--v-white)', fontWeight: 'bold' }" back
      :backStyle="{ color: 'var(--v-white)' }"></s-nav-bar>

    <!-- 主内容区域 - 增加下拉刷新和滚动加载 -->
    <scroll-view class="main-scroll" scroll-y="true" @scrolltolower="loadMore" refresher-enabled
      :refresher-triggered="refreshing" @refresherrefresh="refreshData">
      <view class="main">
        <!-- 总计区域 - 使用CSS变量样式 -->
        <view class="total-section">
          <view class="total-header">
            <view class="left">
              <picker mode="date" fields="month" :value="filterMonth" @change="changeMonth">
                <view class="picker-content">
                  <text class="current-month">{{ currentMonthText }}</text>
                  <s-icon name="arrow" size="16" color="#fff"></s-icon>
                </view>
              </picker>
            </view>
            <view class="right">
              <text class="title">总计:</text>
              <text class="amount">{{ summary.total_amount || 0 }}元</text>
            </view>
          </view>

          <view class="stats-grid">
            <view class="stat-item">
              <text class="label">实收金额(元)</text>
              <text class="value" style="color: var(--v-green)">{{ summary.total_deposit || 0 }}</text>
            </view>
            <view class="stat-item">
              <text class="label">订单金额(元)</text>
              <text class="value">{{ summary.total_amount || 0 }}</text>
            </view>
            <view class="stat-item">
              <text class="label">尾款(元)</text>
              <text class="value" style="color: var(--v-danger)">{{ summary.total_final_payment || 0 }}</text>
            </view>
          </view>
        </view>

        <!-- 订单列表 - 增加交互效果 -->
        <view class="order-list">
          <view class="order-item" v-for="(item, index) in orderList" :key="item.id" @click="viewDetail(item.id)"
            :style="{ 'border-left': `6rpx solid ${getOrderColor(index)}` }">
            <view class="order-header">
              <text class="order-title">{{ item.customer_name || '未命名客户' }}</text>
              <text class="order-amount">总金额:{{ item.total_amount }}元</text>
            </view>

            <view class="order-detail">
              <view class="detail-row">
                <text class="detail-label">订单日期:</text>
                <text class="detail-value">{{ item.order_date }}</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">服务类型:</text>
                <text class="detail-value">{{ item.type || '--' }}</text>
              </view>
            </view>

            <view class="payment-info">
              <text class="payment-label">已付金额:</text>
              <text class="payment-value" style="color: var(--v-green)">{{ item.deposit }}元</text>
              <text class="payment-label">尾款:</text>
              <text class="payment-value" style="color: var(--v-danger)">{{ item.final_payment }}元</text>
            </view>
          </view>

          <!-- 加载更多提示 -->
          <view class="load-more" v-if="loading && !refreshing">
            <s-loading size="20" />
            <text>加载中...</text>
          </view>

          <!-- 没有更多提示 -->
          <view class="no-more" v-else-if="!hasMore && orderList.length > 0">
            <text>没有更多数据了</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import formatDate from "uni_modules/s-ui/utils/formatDate.js";
import sNavBar from '@/uni_modules/s-ui/components/s-nav-bar/s-nav-bar.vue'
import sIcon from '@/uni_modules/s-ui/components/s-icon/s-icon.vue'
import sLoading from '@/pages/extra/components/s-loading/s-loading.vue'

export default {
  components: {
    sNavBar,
    sIcon,
    sLoading
  },
  data() {
    return {
      // 数据状态
      loading: false,
      refreshing: false,
      error: false,
      hasMore: true,
      // 筛选参数
      filterMonth: "",
      // 数据
      summary: {},
      orderList: [],
      pagination: {
        page: 1,
        pageSize: 10,
      },
    };
  },
  computed: {
    currentMonthText() {
      if (!this.filterMonth) return "选择月份";
      const [year, month] = this.filterMonth.split("-");
      return `${year}年${month}月`;
    },
  },
  onLoad() {
    this.filterMonth = formatDate(Date.now(), 'YYYY-MM')
    this.initData();
  },
  methods: {
    // 初始化数据
    async initData() {
      await Promise.all([
        this.fetchSummary(),
        // this.fetchOrders(true)
      ]);
    },

    // 获取汇总数据
    async fetchSummary() {
      try {
        const res = await this.sjuAjax.get("/order/statsByMonth", {
          month: this.filterMonth,
        });
        if (res.code === 200) {
          console.log(res.data);
          this.summary = res.data.stats || {};
          this.orderList = res.data.orders || {};
        }
      } catch (e) {
        console.error("获取汇总数据失败", e);
      }
    },
    // 月份变化
    changeMonth(e) {
      this.filterMonth = e.detail.value;
      this.refreshData();
    },

    // 刷新数据
    refreshData() {
      Promise.all([this.fetchSummary()]);
    },

    // 加载更多
    loadMore() {
      if (!this.hasMore || this.loading) return;
    },

    // 查看详情
    viewDetail(id) {
      uni.navigateTo({
        url: `/pages/order/detail?id=${id}`,
      });
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return "--";
      return dateStr.split(" ")[0];
    },

    // 获取订单颜色
    getOrderColor(index) {
      const colors = ["var(--v-theme)", "var(--v-green)", "#9C27B0", "#FF9800"];
      return colors[index % colors.length];
    },
  },
};
</script>
<style lang="scss">
.revenue-page {
  width: 100vw;
  height: 100vh;
  background: var(--v-bg);
  display: flex;
  flex-direction: column;
}

.main-scroll {
  flex-grow: 1;
  height: 0;
}

.main {
  padding: 30rpx;
  padding-bottom: 120rpx;
}

/* 总计区域 */
.total-section {
  background: var(--v-white);
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  box-shadow: var(--v-shadow);
  overflow: hidden;

  .total-header {
    background: var(--v-theme);
    color: var(--v-bg);
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    padding: 20rpx 30rpx;

    .title {}

    .amount {
      font-weight: bold;
    }
  }

  .stats-grid {
    display: flex;
    justify-content: space-between;

    .stat-item {
      flex: 1;
      text-align: center;
      padding: 15rpx;
      background: rgba(var(--v-theme), 0.05);
      border-radius: 12rpx;
      margin: 0 10rpx;

      .label {
        font-size: 26rpx;
        color: var(--v-gray);
        display: block;
        margin-bottom: 10rpx;
      }

      .value {
        font-size: 36rpx;
        color: var(--v-text);
        font-weight: bold;
      }
    }
  }
}

/* 月份选择 */
.month-picker {
  background: var(--v-white);
  border-radius: 16rpx;
  padding: 20rpx 30rpx;
  margin-bottom: 30rpx;
  box-shadow: var(--v-shadow);

  .picker-content {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .current-month {
      font-size: 32rpx;
      color: var(--v-theme);
      font-weight: bold;
    }
  }
}

/* 订单列表 */
.order-list {
  display: flex;
  flex-direction: column;

  >* {
    margin-bottom: 20rpx;

    /* Replaced gap: 20rpx */
    &:last-child {
      margin-bottom: 0;
      /* Remove margin from last child */
    }
  }

  .order-item {
    background: var(--v-white);
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: var(--v-shadow);
    transition: transform 0.2s;

    &:active {
      transform: scale(0.98);
    }

    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .order-title {
        font-size: 32rpx;
        color: var(--v-text);
        font-weight: bold;
      }

      .order-amount {
        font-size: 28rpx;
        font-weight: bold;
        color: var(--v-theme);
      }
    }

    .order-detail {
      margin-bottom: 20rpx;

      .detail-row {
        display: flex;
        margin-bottom: 10rpx;

        .detail-label {
          font-size: 26rpx;
          color: var(--v-gray);
          width: 180rpx;
        }

        .detail-value {
          font-size: 26rpx;
          color: var(--v-text);
        }
      }
    }

    .payment-info {
      display: flex;
      justify-content: space-between;
      padding-top: 15rpx;
      border-top: 1rpx dashed rgba(var(--v-gray), 0.3);

      .payment-label {
        font-size: 26rpx;
        color: var(--v-gray);
      }

      .payment-value {
        font-size: 26rpx;
        font-weight: bold;
      }
    }
  }

  .load-more,
  .no-more {
    padding: 30rpx;
    text-align: center;
    color: var(--v-gray);
    font-size: 26rpx;
    display: flex;
    justify-content: center;
    align-items: center;

    >* {
      margin-right: 10rpx;

      /* Replaced gap: 10rpx */
      &:last-child {
        margin-right: 0;
        /* Remove margin from last child */
      }
    }
  }

  .no-more {
    padding: 20rpx;
  }
}
</style>